package com.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DBUtil {
    private static String driver = null;
    private static String url = null;
    private static String username = null;
    private static String password = null;

    static {
        Properties properties = new Properties();
        InputStream is = DBUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
        try {
            properties.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        driver = properties.getProperty("driver");
        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.getProperty("password");
    }

    public static Connection getConnection() {
        Connection con = null;
        try {
            Class.forName(driver);
            con = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return con;
    }

    public static ResultSet query(Connection con, PreparedStatement pre, ResultSet rs, String sql, Object[] params) throws SQLException {
        pre = con.prepareStatement(sql);
        if (params!=null){
            for (int i = 0; i < params.length; i++) {
                pre.setObject(i + 1, params[i]);
            }
        }
        rs = pre.executeQuery();
        return rs;
    }

    public static int execute(Connection con, PreparedStatement pre, String sql, Object[] params) throws SQLException {
        pre = con.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            pre.setObject(i + 1, params[i]);
        }
        int updateRows = pre.executeUpdate();
        return updateRows;
    }

    public static boolean closeResource(Connection con, PreparedStatement pre, ResultSet rs) {
        boolean flag = true;
        if (rs != null) {
            try {
                rs.close();
                rs = null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag = false;
            }
        }
        if (pre != null) {
            try {
                pre.close();
                pre = null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag = false;
            }
        }
        if (con != null) {
            try {
                con.close();
                con = null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag = false;
            }
        }
        return flag;
    }
}
